<template>
  <div class="teams-management">
    <div class="header">
      <el-button type="primary" @click="handleAdd">添加团队</el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="团队名称">
        <el-input v-model="searchForm.name" placeholder="请输入团队名称" clearable />
      </el-form-item>
      <el-form-item label="团队组长">
        <el-select v-model="searchForm.leader" placeholder="请选择团队组长" clearable>
          <el-option
            v-for="leader in leaders"
            :key="leader.id"
            :label="leader.name"
            :value="leader.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 团队统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总团队数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ teamsList.length }}</div>
            <div class="trend">
              <span>较上月</span>
              <span class="up">+2</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总成员数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ totalMembers }}</div>
            <div class="trend">
              <span>较上月</span>
              <span class="up">+5</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均团队规模</span>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ averageTeamSize }}</div>
            <div class="trend">
              <span>较上月</span>
              <span class="up">+0.5</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃团队数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ activeTeams }}</div>
            <div class="trend">
              <span>较上月</span>
              <span class="up">+1</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-table :data="teamsList" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="团队名称" />
      <el-table-column prop="leader" label="团队组长" />
      <el-table-column prop="memberCount" label="成员数量" />
      <el-table-column prop="performance" label="团队绩效">
        <template #default="{ row }">
          <el-progress 
            :percentage="row.performance" 
            :color="getPerformanceColor(row.performance)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewDetails(row)">详情</el-button>
          <el-button type="primary" link @click="handleViewMembers(row)">查看组员</el-button>
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 团队详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      :title="currentTeam.name + ' - 团队详情'"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="团队名称">{{ currentTeam.name }}</el-descriptions-item>
        <el-descriptions-item label="团队组长">{{ currentTeam.leader }}</el-descriptions-item>
        <el-descriptions-item label="成员数量">{{ currentTeam.memberCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentTeam.createTime }}</el-descriptions-item>
        <el-descriptions-item label="团队绩效">
          <el-progress 
            :percentage="currentTeam.performance" 
            :color="getPerformanceColor(currentTeam.performance)"
          />
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentTeam.status === 'active' ? 'success' : 'danger'">
            {{ currentTeam.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentTeam.remark }}</el-descriptions-item>
      </el-descriptions>

      <div class="performance-chart">
        <div class="chart-title">团队绩效趋势</div>
        <div class="chart-container" ref="performanceChartRef"></div>
      </div>
    </el-dialog>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加团队' : '编辑团队'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="团队名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入团队名称" />
        </el-form-item>
        <el-form-item label="团队组长" prop="leader">
          <el-select v-model="form.leader" placeholder="请选择团队组长">
            <el-option
              v-for="leader in leaders"
              :key="leader.id"
              :label="leader.name"
              :value="leader.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="团队成员" prop="members">
          <el-select
            v-model="form.members"
            multiple
            filterable
            placeholder="请选择团队成员"
            style="width: 100%"
          >
            <el-option
              v-for="member in availableSalesMembers"
              :key="member.id"
              :label="member.name"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="active">在职</el-radio>
            <el-radio value="inactive">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看组员对话框 -->
    <el-dialog
      v-model="membersDialogVisible"
      :title="currentTeam.name + ' - 团队成员'"
      width="800px"
    >
      <div class="members-header">
        <el-button type="primary" @click="handleAddMember">添加组员</el-button>
        <el-input
          v-model="memberSearch"
          placeholder="搜索成员"
          style="width: 200px; margin-left: 10px"
          clearable
        />
      </div>
      <el-table :data="filteredMembers" style="width: 100%">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="joinTime" label="加入时间" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="row.role === 'leader' ? 'warning' : 'info'">
              {{ row.role === 'leader' ? '组长' : '组员' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              v-if="row.role !== 'leader'"
              type="danger" 
              link 
              @click="handleRemoveMember(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加组员对话框 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      title="添加组员"
      width="500px"
    >
      <el-form
        ref="addMemberFormRef"
        :model="addMemberForm"
        :rules="addMemberRules"
        label-width="80px"
      >
        <el-form-item label="选择组员" prop="memberId">
          <el-select 
            v-model="addMemberForm.memberId" 
            placeholder="请选择组员" 
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="member in filteredAvailableMembers"
              :key="member.id"
              :label="member.name"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="addMemberForm.role">
            <el-radio value="member">组员</el-radio>
            <el-radio value="leader">组长</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddMemberSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const loading = ref(false)
const dialogVisible = ref(false)
const membersDialogVisible = ref(false)
const addMemberDialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const addMemberFormRef = ref(null)
const currentTeam = ref({})
const memberSearch = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const searchForm = reactive({
  name: '',
  leader: '',
  status: ''
})

const form = reactive({
  name: '',
  leader: '',
  members: [],
  status: 'active',
  remark: ''
})

const addMemberForm = reactive({
  memberId: '',
  role: 'member'
})

const rules = {
  name: [{ required: true, message: '请输入团队名称', trigger: 'blur' }],
  leader: [{ required: true, message: '请选择团队组长', trigger: 'change' }],
  members: [{ required: true, message: '请选择团队成员', trigger: 'change' }]
}

const addMemberRules = {
  memberId: [{ required: true, message: '请选择组员', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 模拟数据
const teamsList = ref([
  {
    id: 1,
    name: '销售一组',
    leader: '李四',
    memberCount: 5,
    createTime: '2024-03-20 10:00:00',
    status: 'active',
    remark: '主要负责抖音渠道客户',
    members: [
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        email: 'zhangsan@example.com',
        joinTime: '2024-03-20 10:00:00',
        role: 'member'
      },
      {
        id: 2,
        name: '王五',
        phone: '13900139000',
        email: 'wangwu@example.com',
        joinTime: '2024-03-20 10:00:00',
        role: 'leader'
      }
    ]
  }
])

const leaders = ref([
  { id: 1, name: '李四' },
  { id: 2, name: '王五' }
])

// 模拟可添加的成员列表
const availableMembers = ref([
  { id: 3, name: '赵六' },
  { id: 4, name: '钱七' },
  { id: 5, name: '孙八' }
])

// 模拟销售人员数据
const salesMembers = ref([
  { id: 1, name: '张三', phone: '13800138000', email: 'zhangsan@example.com' },
  { id: 2, name: '李四', phone: '13900139000', email: 'lisi@example.com' },
  { id: 3, name: '王五', phone: '13700137000', email: 'wangwu@example.com' },
  { id: 4, name: '赵六', phone: '13600136000', email: 'zhaoliu@example.com' },
  { id: 5, name: '钱七', phone: '13500135000', email: 'qianqi@example.com' }
])

// 计算属性：过滤后的成员列表
const filteredMembers = computed(() => {
  if (!memberSearch.value) return currentTeam.value.members || []
  const search = memberSearch.value.toLowerCase()
  return (currentTeam.value.members || []).filter(member => 
    member.name.toLowerCase().includes(search) ||
    member.phone.includes(search) ||
    member.email.toLowerCase().includes(search)
  )
})

// 计算属性：过滤后的可选成员列表（排除已在团队中的成员）
const filteredAvailableMembers = computed(() => {
  const currentMemberIds = new Set((currentTeam.value.members || []).map(m => m.id))
  return availableMembers.value.filter(member => !currentMemberIds.has(member.id))
})

// 计算属性：可选的销售人员（排除已经是其他团队组长的人）
const availableSalesMembers = computed(() => {
  const leaderIds = new Set(leaders.value.map(l => l.id))
  return salesMembers.value.filter(member => !leaderIds.has(member.id))
})

// 计算属性：总成员数
const totalMembers = computed(() => {
  return teamsList.value.reduce((sum, team) => sum + team.memberCount, 0)
})

// 计算属性：平均团队规模
const averageTeamSize = computed(() => {
  return teamsList.value.length ? (totalMembers.value / teamsList.value.length).toFixed(1) : 0
})

// 计算属性：活跃团队数
const activeTeams = computed(() => {
  return teamsList.value.filter(team => team.status === 'active').length
})

// 获取绩效颜色
const getPerformanceColor = (percentage) => {
  if (percentage >= 80) return '#67C23A'
  if (percentage >= 60) return '#E6A23C'
  return '#F56C6C'
}

const handleSearch = () => {
  // 实现搜索逻辑
  console.log('搜索条件：', searchForm)
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    name: '',
    leader: '',
    members: [],
    status: 'active',
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    ...row,
    members: row.members.map(m => m.id)
  })
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该团队吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除API
    ElMessage.success('删除成功')
  })
}

const handleViewMembers = (row) => {
  currentTeam.value = row
  memberSearch.value = ''
  membersDialogVisible.value = true
}

const handleAddMember = () => {
  addMemberForm.memberId = ''
  addMemberForm.role = 'member'
  addMemberDialogVisible.value = true
}

const handleAddMemberSubmit = async () => {
  if (!addMemberFormRef.value) return
  
  await addMemberFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用添加组员API
      const member = availableMembers.value.find(m => m.id === addMemberForm.memberId)
      if (member) {
        const newMember = {
          ...member,
          joinTime: new Date().toLocaleString(),
          role: addMemberForm.role
        }
        currentTeam.value.members.push(newMember)
        currentTeam.value.memberCount = currentTeam.value.members.length
        
        // 如果是组长，更新团队组长信息
        if (addMemberForm.role === 'leader') {
          currentTeam.value.leader = member.name
        }
        
        ElMessage.success('添加成功')
        addMemberDialogVisible.value = false
      }
    }
  })
}

const handleRemoveMember = (member) => {
  ElMessageBox.confirm('确定要移除该组员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用移除组员API
    const index = currentTeam.value.members.findIndex(m => m.id === member.id)
    if (index !== -1) {
      currentTeam.value.members.splice(index, 1)
      currentTeam.value.memberCount = currentTeam.value.members.length
      ElMessage.success('移除成功')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用添加/编辑API
      const selectedMembers = salesMembers.value.filter(m => form.members.includes(m.id))
      const newTeam = {
        ...form,
        members: selectedMembers.map(m => ({
          ...m,
          joinTime: new Date().toLocaleString(),
          role: m.id === form.leader ? 'leader' : 'member'
        })),
        memberCount: selectedMembers.length
      }
      
      if (dialogType.value === 'add') {
        teamsList.value.push(newTeam)
      } else {
        const index = teamsList.value.findIndex(t => t.id === newTeam.id)
        if (index !== -1) {
          teamsList.value[index] = newTeam
        }
      }
      
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
      dialogVisible.value = false
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 实现分页逻辑
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 实现分页逻辑
}

// 团队详情相关
const detailsDialogVisible = ref(false)
const performanceChartRef = ref(null)
let performanceChart = null

const handleViewDetails = (row) => {
  currentTeam.value = row
  detailsDialogVisible.value = true
  // 延迟初始化图表，确保DOM已渲染
  setTimeout(initPerformanceChart, 0)
}

const initPerformanceChart = () => {
  if (performanceChart) {
    performanceChart.dispose()
  }
  
  performanceChart = echarts.init(performanceChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      max: 100
    },
    series: [{
      data: [65, 70, 75, 80, 85, 90],
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }
  performanceChart.setOption(option)
}

// 监听窗口大小变化，重新渲染图表
window.addEventListener('resize', () => {
  if (performanceChart) {
    performanceChart.resize()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (performanceChart) {
    performanceChart.dispose()
  }
  window.removeEventListener('resize', () => {
    if (performanceChart) {
      performanceChart.resize()
    }
  })
})
</script>

<style scoped>
.teams-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

.card-content .number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.card-content .trend {
  font-size: 14px;
  color: #909399;
}

.card-content .trend .up {
  color: #67C23A;
  margin-left: 5px;
}

.card-content .trend .down {
  color: #F56C6C;
  margin-left: 5px;
}

.members-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.performance-chart {
  margin-top: 30px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.chart-container {
  height: 300px;
}
</style>